package com.cpi.cornpp.version.action;

import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.cpi.cornpp.common.exception.CornPPException;
import com.cpi.cornpp.monthsperiods.services.MonthsPeriodsService;
import com.cpi.cornpp.version.exception.VersionException;
import com.cpi.cornpp.version.services.VersionService;

public class ShowAddVersionAction extends Action {
	private final static String CUSTOM_EXCEPTION = "custom_exception";//$NON-NLS-1$
	private static final String SUCCESS_FORWARD = "toSuccess";
	private static final String FAILURE_FORWARD = "error";
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws VersionException{
		int actualMonth = 0;
		MonthsPeriodsService monthPeriodService = null;
		VersionService versionService = null;
		List monthPeriodsView = null;
		List versionsView = null;
		HttpSession session = null;
		ActionForward forward = null;
		
		forward = mapping.findForward(FAILURE_FORWARD);
		session = request.getSession(false);
		
		try{
			
			monthPeriodService = new MonthsPeriodsService();
			versionService = new VersionService();
			
			actualMonth = monthPeriodService.actualMonthPeriod();
			monthPeriodsView = monthPeriodService.listOfMonthsPeriods();
			versionsView = versionService.list(0, true);
			
			request.setAttribute("actualMonth", new Integer(actualMonth));
			request.setAttribute("actualYear", new Integer(Calendar.getInstance().get(Calendar.YEAR)));
			request.setAttribute("monthPeriods", monthPeriodsView);
			request.setAttribute("versions", versionsView);
			
			forward = mapping.findForward(SUCCESS_FORWARD);
			
		} catch (VersionException versionException){
			session.setAttribute(CUSTOM_EXCEPTION, versionException);
			throw versionException;
		} catch (Exception e){
			VersionException versionException=null;
			e.printStackTrace(System.out);
			versionException= new VersionException(e , CornPPException.LAYER_ACTION,CornPPException.ACTION_LISTS);
			session.setAttribute(CUSTOM_EXCEPTION, versionException);
			throw versionException;
		}
		
		return forward;
	}
}